using Identity.Domain.ValueObjects;
using Identity.Infrastructure.Persistence.Entities;
using Microsoft.EntityFrameworkCore;

namespace Identity.Infrastructure.Persistence.Configurations
{
    public class ApiPermissionBindingConfiguration: IEntityTypeConfiguration<ApiPermissionBinding>
    {
    

        public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<ApiPermissionBinding> builder)
        {
            builder.ToTable("ApiPermissionBindings");
            builder.HasKey(p => p.ResourceId);
            builder.HasIndex(p => new { p.ResourceId, p.FromServiceName }).IsUnique();
            builder.Property(p => p.ResourceId).IsRequired().HasMaxLength(100);
            builder.Property(p => p.Description).HasMaxLength(500);
            builder.Property(p => p.FromServiceName).IsRequired().HasMaxLength(100);
            builder.Property(p => p.IsActive).IsRequired();
            builder.Property(p => p.PermissionScope)
                .HasConversion(
                    v => v.Value, // 存数据库 (string)
                    v => string.IsNullOrWhiteSpace(v)
                        ? PermissionScope.Local // 如果数据库为空，使用默认值
                        : PermissionScope.From(v) // 正常转换
                )
                .HasColumnName("PermissionScope")
                
                .IsRequired()
                .HasMaxLength(50);
            // 外键关系
            builder.HasOne(p => p.Permission)
                .WithMany() // 如果 Permission 有一个集合属性来表示多个 PermissionKeyResourceId，可以在这里指定
                .HasForeignKey(p => p.permissionId)
                .OnDelete(DeleteBehavior.SetNull); // 根据需要设置删除行为
        }

       
    }
}